﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Teriri.File.UniversalLib.Helper
{
    /// <summary>
    /// 简单配置项帮助类
    /// </summary>
    public static class ConfigHelper
    {
        private readonly static Dictionary<string, object> Configs = new();

        /// <summary>
        /// 读取配置
        /// </summary>
        public static IConfigurationRoot ReadConfig<T>(this IConfigurationRoot configuration) where T : class
        {
            var instance = Activator.CreateInstance(typeof(T));

            foreach (var property in typeof(T).GetProperties())
            {
                string value = configuration.GetSection($"{typeof(T).Name}:{property.Name}").Value;

                if (property.PropertyType == typeof(string))
                    property.SetValue(instance, value, null);
                else if (property.PropertyType == typeof(int))
                    property.SetValue(instance, int.Parse(value), null);
                else if (property.PropertyType == typeof(double))
                    property.SetValue(instance, double.Parse(value), null);
                else if (property.PropertyType == typeof(bool))
                    property.SetValue(instance, bool.Parse(value), null);
            }

            Configs[typeof(T).FullName] = instance;
            return configuration;
        }

        /// <summary>
        /// 获取配置
        /// </summary>
        public static T GetConfig<T>() where T : class
        {
            if (Configs.TryGetValue(typeof(T).FullName, out var value))
                return value as T;
            else
                return default;
        }
    }
}
